# This script will read in a single AWAP data file (5k res - Ozwide)
# And convert to it 250 m res WTplusBuffer size

# Obtain command line arguments from .sh file

args=(commandArgs(TRUE))

# Evaluate the arguments for use in this script

for(i in 1:length(args)) 
	
	{
		
	eval(parse(text=args[[i]]))
 
	}

# Load the necessary libraries
necessary=c('SDMTools')
#check if library is installed
installed = necessary %in% installed.packages()
#if library is not installed, install it
if (length(necessary[!installed]) >=1) install.packages(necessary[!installed], dep = T)
#load the libraries
for (lib in necessary) library(lib,character.only=T)	
	
# This is the argument to base the script on
# Comment out when finished
	
#tfile="/home1/99/jc152199/MicroclimateStatisticalDownscale/AWAPASCII/RawAWAP//Tmin/2008/tmin.2008042520080425.grid.gz"

# Define out directory

base.dir = '/home1/99/jc152199/MicroclimateStatisticalDownscale/AWAPASCII/RawAWAP/'
out.dir = '/home1/99/jc152199/MicroclimateStatisticalDownscale/250mASCII/'

# Read in the AWAP ASCII

tasc = read.asc.gz(tfile)

# Read in base.pos

base.pos = read.csv(paste(base.dir,'WTplusBuffer.rowcol.latlong.csv',sep=''),header=T)

# Read in base.asc

base.asc = read.asc('/home1/99/jc152199/MicroclimateStatisticalDownscale/250mASCII/Analysis_Mask/Analysis_Mask_ASCII/AnalysisMask_WTplusbuffer_LatLong_WGS1984_250mres.asc')
base.asc[,] = NA

# Create 250 m res AWAP ASCII size of WTplusbuffer

base.asc[cbind(base.pos$row,base.pos$col)] = extract.data(cbind(base.pos$lat,base.pos$long),tasc)

# Write out ASCII to appropriate directory, use an if command to make sure the solar and tmin/tmax files are labelled appropriately

if (is.na(grep('solar',tfile)[1])==T) write.asc.gz(base.asc,paste(out.dir,'/',substr(tfile,72,75),'/',substr(tfile,77,80),'/',substr(tfile,87,94),sep='')) else write.asc.gz(base.asc,paste(out.dir,'/',substr(tfile,72,76),'/',substr(tfile,78,81),'/',substr(tfile,89,96),sep=''))

# Done

	
